#!/usr/bin/env python
import json

import pika
import time

import requests

credentials = pika.PlainCredentials(username="test", password="test")
connection = pika.BlockingConnection(
    # pika.ConnectionParameters(host='192.168.159.135', credentials=credentials)
    pika.ConnectionParameters(host='192.168.198.132', credentials=credentials)

)
channel = connection.channel()

print(' [*] Waiting for messages. To exit press CTRL+C')


def pong(data):
    # 发送任务
    pong_channel.basic_publish(
        exchange='',
        routing_key='recv',
        body=data.encode("utf8"),
        properties=pika.BasicProperties(
            delivery_mode=2,  # make message persistent
        ))
    time.sleep(0.1)


def callback(ch, method, properties, body):

    # print(" [x] Received %r" % body.decode())
    # 取出数据后进行处理
    body = json.loads(body)
    print(f"Scanning {body.get('IP')}:{body.get('PORT')}")
    message = f"{body.get('IP')}:{body.get('PORT')} is OPEN"
    # 确认数据已收到
    ch.basic_ack(delivery_tag=method.delivery_tag)
    # 将处理结果返回给recv队列
    pong(message)


if __name__ == '__main__':
    pong_channel = connection.channel()
    pong_channel.queue_declare(queue='recv', durable=True)
    channel.basic_qos(prefetch_count=10)
    # 从send队列中取出数据
    channel.basic_consume(queue='send', on_message_callback=callback)

    channel.start_consuming()